#include "Dwarf.Unmanaged.Hybrid.h"

static DLLParseArguments pDLLParseArguments;        // method 'parseArguments' loaded from CliTools.unmanaged.dll
static DLLUsage pDLLUsage;                          // method 'usage' loaded from CliTools.unmanaged.dll
static DLLStart pDLLStart;                          // method 'start' [time count] loaded from CliTools.unmanaged.dll
static DLLStop pDLLStop;                            // method 'stop' [time count] loaded from CliTools.unmanaged.dll
static HINSTANCE hInstDll;                          // instance of CliTools.unmanaged.dll

Settings :: Settings()
{
    inputFile = new char[BUFFER_SIZE];
    resultFile = new char[BUFFER_SIZE];
    profileFile = new char[BUFFER_SIZE];

    inputFile[0] = resultFile[0] = profileFile[0] ='\0';
}

Settings :: ~Settings()
{
    delete inputFile;
    delete resultFile;
    delete profileFile;
}

// Parse input file into solver's structures.
int Settings::parseConfigFile(Solver* solver) 
{
    FILE *file;
    // Open the file to read from.
    if( fopen_s(&file, inputFile, "rb")) 
    {
        printf("Can't open config file!\r\n");
        (pDLLUsage)();

        return -1;
    }

    printf("\r\nParse input file...\r\n");

    fscanf_s(file, "%d\n", &solver->length);
    //initialization
    solver->init();

    int i,j;
    i = j = 0;
    int re = 0;
    int im = 0;
    while(!feof(file) && j < solver->length)
    {
        fscanf_s(file, "%i %i;", &re, &im);
        solver->complexArray[j][i].real((double)re);
        solver->complexArray[j][i].imag((double)im);
        i ++;

        if (i == solver->length) 
        {   
            i = 0;
            j++;
        } 
    }    

    fclose(file);

    return 0;
}

int Settings::init(int argc, char** argv, Solver *solver) 
{

    // Load the dll into the address space
    hInstDll = LoadLibraryA("CliTools");
    if(!hInstDll)
    {
        printf("Error while loading CliTools.dll.");
        return -1;
    }

    // Retrieve a pointer to the factory function
    pDLLParseArguments = 
        (DLLParseArguments) GetProcAddress(hInstDll, "parseArguments");

    pDLLUsage =
        (DLLUsage) GetProcAddress(hInstDll, "usage");

    pDLLStart = 
        (DLLStart) GetProcAddress(hInstDll, "start");

    pDLLStop = 
        (DLLStop) GetProcAddress(hInstDll, "stop");

    if ((pDLLParseArguments)(argc, argv, &inputFile, &profileFile,  &resultFile)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }
    //Parse input file. 
    if (parseConfigFile(solver)) 
    {
        FreeLibrary(hInstDll); 
        return -1;
    }
    //Write settings if it's needed.
    writeSettings(solver);
    return 0;
}

// Start the time count.
void Settings::start() 
{
    (pDLLStart)();
}

void Settings::finish(Solver *solver)
{
    double time;
    (pDLLStop)(&time);
    //Release dll.
    FreeLibrary(hInstDll);

    printf("\r\n");
    printf("Clock time (sec):  %.8f \r\n", time);  
    printf("\r\nWrite the result of computing...\r\n");
    FILE* outputResult = 0;
    FILE* outputProfile = 0;

    if( fopen_s(&outputProfile, profileFile , "wb")) 
    {
        printf("Can't create profile file!\r\n");            
        fclose(outputProfile);
        return;
    }

    if( fopen_s(&outputResult, resultFile , "wb")) 
    {
        printf("Can't create result file!\r\n");   
        fclose(outputResult);
        return;
    }

    fprintf(outputProfile, "#Dwarf name:%s\r\n", DWARF_NAME);

    char tmpbuf[BUFFER_SIZE];
    _tzset();

    _strdate_s( tmpbuf, BUFFER_SIZE );
    fprintf(outputProfile, "#Time: %s ",tmpbuf);

    _strtime_s( tmpbuf, BUFFER_SIZE );
    fprintf(outputProfile, "%s \r\n",tmpbuf);

    fprintf(outputProfile, "#Length: %i\r\n", solver->length);
    fprintf(outputProfile, "#Result time (sec): %.8f\r\n", time);
    fprintf(outputResult,  "#Result domain:\r\n");
    int yLength = solver->length;
    if( LENGTH_FOR_PRINT < yLength)
    {
        yLength = LENGTH_FOR_PRINT;
    }

    for(int i = 0; i < yLength; i++ ){
        for(int j = 0; j < solver->length; j++){
            fprintf(outputResult," %.1f %.1f ;",solver->complexArray[i][j].real(),solver->complexArray[i][j].imag());
        }
        fprintf(outputResult,"\r\n");
    }
    fprintf(outputResult, "\r\n");
    fprintf(outputProfile, "#eof");

    fclose(outputProfile);
    fclose(outputResult);

}

// Write settings.
void Settings::writeSettings(Solver *solver)
{
    // Write general settings.
    printf("Kernel settings summary  : \r\n");
    printf("Dwarf name               : %s \r\n", DWARF_NAME);
    printf("#Length                  : %d \r\n", solver->length);
    printf("Input file               : %s \r\n", inputFile);
    printf("Output file              : %s \r\n", resultFile);    
    printf("\r\n");
}